package xlcao.sohutv.ui;

import java.util.ArrayList;

import xlcao.sohutv.R;
import xlcao.sohutv.adapter.TvlistAdapter;
import xlcao.sohutv.bean.TVInfo;
import xlcao.sohutv.db.DBOperator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;

public final class MeleTVListFragment extends android.support.v4.app.ListFragment {
	private OnTVSelectedListener tvSelectedListener;
	private ArrayList<TVInfo> TVlist;
	private DBOperator dbo = null;
	private int mode = 0; // 0 all 1 fav
	private int longClickPosition = 0;
	private int CurALLPos = 0;
	private int CurFAVPos = 0;
	private static final int ADD_TO_FAV_DIALOG = 101;
	private static final int DELETE_FROM_FAV_DIALOG = 102;

	@Override
	public void onListItemClick(ListView l, final View v, int position, final long id) {

		l.requestFocus();
		tvSelectedListener.onTVSelected(((TVInfo) getListView().getAdapter()
				.getItem(position)).getUrl(), ((TVInfo) getListView()
				.getAdapter().getItem(position)).getTitle());
		((TvlistAdapter) getListView().getAdapter()).setSelectedItem(position);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		dbo = new DBOperator(getActivity().getApplicationContext());

		// View header =
		// getActivity().getLayoutInflater().inflate(R.layout.header, null);

	}

	void refreshItems(int type) {
		// type 0 all ,type 1 fav
		mode = type;
		TVlist = dbo.getItems(type);

		if (TVlist == null && type == 1) {
			setListAdapter(null);
			return;
		}

		int size = TVlist.size();

		if (size == 0 && type == 1) {
			setListAdapter(null);
			return;
		}

		TvlistAdapter adp = new TvlistAdapter(getActivity(), R.layout.list_item);
		adp.setTVInfoList(TVlist);
		setListAdapter(adp);

	}

	void deleteFavItems() {
		if (dbo != null) {
			dbo.deleteFavRows();
			refreshItems(mode);
		}

	}
	private Handler mHideHandler = new Handler();
	private Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			hideMe();
		}
	};
	
	void delayedHide(int delayMillis) {
		MeleTVViewerFragment viewer = (MeleTVViewerFragment) getFragmentManager().findFragmentById(R.id.tvview_fragment);
		if ( viewer != null && viewer.isPlayering()) {
			mHideHandler.removeCallbacks(mHideRunnable);
			mHideHandler.postDelayed(mHideRunnable, delayMillis);
		}
	}
	
	private void hideMe() {
		RelativeLayout ll = (RelativeLayout) getActivity().findViewById(R.id.listlayout);
		if ( ll!= null && ll.getVisibility() == View.VISIBLE) {
			android.animation.AnimatorSet set = new AnimatorSet();
			set.playTogether(ObjectAnimator.ofFloat(ll, "translationX",
					ll.getWidth(), 0)
	
			);
			set.setDuration(200).start();
			ll.setVisibility(View.GONE);
			MeleTVViewerFragment viewer = (MeleTVViewerFragment) getFragmentManager().findFragmentById(R.id.tvview_fragment);
			viewer.moveToCenter();
		}
	}
	@Override
	public void onActivityCreated(Bundle savedState) {
		super.onActivityCreated(savedState);
		getListView().setOnItemLongClickListener(mItemLongClick);
		getListView().setCacheColorHint(0);
		// refreshItems(this.mode);
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		getListView().setItemsCanFocus(true);
		getListView().requestFocus();
		// getListView().setSelection(0);
		getListView().setOnScrollListener(mScrollListener);
		getListView().setBackgroundColor(Color.BLACK);
		getListView().setSelection(0);

	}

	private OnScrollListener mScrollListener = new OnScrollListener() {

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			if (mode == 0) {
				CurALLPos = firstVisibleItem;
            }
            // getListView().getSelectedItemPosition();
			else if (mode == 1) {
				CurFAVPos = firstVisibleItem;
            }
            
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				if (mode == 0) {
					CurALLPos = view.getFirstVisiblePosition();
                }
                // getListView().getSelectedItemPosition();
				else if (mode == 1) {
					CurFAVPos = view.getFirstVisiblePosition();
                }

			}
		}

	};

	/**
	 * Long press on list, remove playlist, ask for confirmation before
	 */

	private OnItemLongClickListener mItemLongClick = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> adapterView, View arg1,
				int position, long arg3) {
			longClickPosition = position;
			if (mode == 0) {
				showDialog(ADD_TO_FAV_DIALOG); // add to fav
			} else {
				showDialog(DELETE_FROM_FAV_DIALOG); // delete from
													// fav
			}
			return true;
		}

	};

	private void showDialog(int id) {
		switch (id) {

		case ADD_TO_FAV_DIALOG:
			new AlertDialog.Builder(getActivity())
					.setTitle(R.string.ADD_TO_FAV_CONFIRM_MSG)
					.setPositiveButton(R.string.OK,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									TVInfo tvinfo = TVlist
											.get(longClickPosition);
									tvinfo.setIsCollected(1);
									dbo.updateRow(tvinfo);
									refreshItems(mode);
								}
							}).setNegativeButton(R.string.RETURN, null)
					.create().show();
			return;
		case DELETE_FROM_FAV_DIALOG:
			new AlertDialog.Builder(getActivity())
					.setTitle(R.string.DELTE_FROM_FAV_CONFIRM_MSG)
					.setPositiveButton(R.string.DELETE,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									TVInfo tvinfo = TVlist
											.get(longClickPosition);
									tvinfo.setIsCollected(0);
									dbo.updateRow(tvinfo);

									refreshItems(mode);
								}
							}).setNegativeButton(R.string.CANCEL, null)
					.create().show();
			return;

		default:
			return;
		}
	}

	public interface OnTVSelectedListener {
		void onTVSelected(String tvUrl, String tvTitle);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			tvSelectedListener = (OnTVSelectedListener) activity;

		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnTutSelectedListener");
		}
	}

	private void setTVListInfo(ArrayList<TVInfo> tvlist) {
		this.TVlist = tvlist;
	}

	void savePos() {
		if (mode == 0) {
			CurALLPos = getListView().getSelectedItemPosition();
        }
        
		else if (mode == 1) {
			CurFAVPos = getListView().getSelectedItemPosition();
        }
        
	//	Log.d("playvideo","CurALLPos is " + CurALLPos + " CurFAVPos is " + CurFAVPos);
	}

	void loadPos() {
		if (mode == 0) {
			getListView().setSelection(CurALLPos);
        }
        
		else if (mode == 1) {
			getListView().setSelection(CurFAVPos);
        }
        
		
		getListView().requestFocus();
	}

}
